<template>
  <div class="login-box">
    <div class="login-form">
      <div>
        <div class="label"><label>用户名：</label></div>
        <el-input type="text" v-model="name" />
      </div>
      <div>
        <div class="label"><label>密 码：</label></div>
        <el-input type="password" v-model="pwd" />
      </div>
      <div>
        <div class="label"><label>角 色：</label></div>
        <el-radio-group v-model="role">
          <el-radio :label="0">普通用户</el-radio>
          <el-radio :label="1">管理员</el-radio>
          <el-radio :label="2">匿名</el-radio>
        </el-radio-group>
      </div>
      <div>
        <el-button type="primary" @click="login">登录</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import {
  ElInput,
  ElRadio,
  ElRadioGroup,
  ElButton,
  ElMessage,
} from "element-plus";
import constants from "../constants";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { reactive, toRefs } from "vue";
import http from "../api/http";
export default {
  components: { ElInput, ElRadio, ElRadioGroup, ElButton, ElMessage },
  setup() {
    const router = useRouter();
    const store = useStore();
    const state = reactive({ name: "", role: 0, pwd: "" });
    const login = () => {
      if (state.role !== 2) {
        if (!state.name || !state.pwd) {
          ElMessage({
            type: "error",
            message: "用户名或密码不能为空",
          });
          return;
        }
      }

      http.get("/data.json").then((res) => {
        let roleList = [];
        roleList =
          state.role === 1 ? res.permissions.admin : res.permissions.user;
        localStorage.setItem(
          constants.UserInfo,
          JSON.stringify({ name: state.name , role: roleList })
        );
        store.commit(
          constants.SetUserInfo,
          JSON.stringify({ name: state.name , role: roleList })
        );
        let token =
          "djsdakfjlksdfjlsdf.sdkljfsdjfoiwendcwoeifkjlsdjfokesdjhndlk.dkjvkneoidknfiejfdkjdkljdjkl";
        localStorage.setItem(constants.Token, token);
        store.commit(constants.SetToken, token);
        router.push("/");
      });
    };

    return {
      ...toRefs(state),
      login,
    };
  },
};
</script>
<style lang="less">
.login-box {
  position: absolute;
  width: 100%;
  height: 100%;
  bottom: 0;
  background-color: rgb(200, 200, 169);
  text-align: center;
  & .login-form {
    position: absolute;
    width: 450px;
    height: 300px;
    box-sizing: border-box;
    left: 55%;
    top: 40%;
    transform: translate(-255px, -150px);
    background-color: rgb(249, 205, 173);
    border-radius: 10px;
    box-shadow: 15px 15px 15px;
    & div {
      margin-top: 8px;
    }
    & label {
      display: inline-block;
      color: #fff;
      width: 80px;
      text-align: left;
    }
  }
}
.label {
  text-align: left;
  margin-left: 10px;
}
</style>